import 'dart:io' show Platform;
import 'dart:ui';
import 'package:bit_fury/controller/invite_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';

import 'controller/admob_controller.dart';
import 'controller/auth_controller.dart';
import 'controller/contract_controller.dart';
import 'controller/setting_controller.dart';
import 'controller/home_controller.dart';
import 'controller/language_controller.dart';
import 'controller/navigation_controller.dart';
import 'controller/payment_controller.dart';
import 'controller/wallet_controller.dart';
import 'http/http_agent.dart';
import 'model/app_translations.dart';
import 'routes/app_routes.dart';
import 'service/analytics_service.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();

    if (Platform.isIOS) {
    await InAppPurchaseStoreKitPlatform.enableStoreKit1();
  }

    // 强制竖屏
  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);

  // 添加错误处理，防止Firebase初始化失败导致应用崩溃
  try {
    await Firebase.initializeApp();
    
    // 初始化 Firebase Analytics
    FirebaseAnalytics.instance;
    
    // 初始化 Firebase Crashlytics
    FlutterError.onError = (errorDetails) {
      FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
    };
    // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics
    PlatformDispatcher.instance.onError = (error, stack) {
      FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
      return true;
    };
    
    print('Firebase初始化成功');
  } catch (e) {
    print('Firebase初始化失败: $e');
    // 在这里不要抛出异常，让应用继续运行
  }

  await GetStorage.init();

  // 配置系统UI以支持Android 15无边框设计
  if (Platform.isAndroid) {
    // 使用 edgeToEdge 模式，避免使用已弃用的 setSystemUIOverlayStyle API
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  }

   // 初始化HttpAgent
  await HttpAgent().init();

  // 记录应用启动事件
  await AnalyticsService.logEvent(
    name: 'app_open',
    parameters: {
      'platform': Platform.operatingSystem,
    },
  );

  // 仅 Android 初始化 AdMobController
  Get.put(AdMobController());

  // 初始化全局控制器
  Get.put(PaymentController());

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'BitPlanera',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: const Color(0xFF1A1A1A),
        brightness: Brightness.dark,
      ),
      translations: AppTranslations(),
      locale: const Locale('en', 'US'),
      fallbackLocale: const Locale('en', 'US'),
      getPages: RouteManger.routes,
      initialRoute: AppRoutes.startupAuth,
      initialBinding: AppBinding(), // 使用单独 binding 管理依赖注入
    );
  }
}

// ✳️ 把控制器绑定单独抽离
class AppBinding extends Bindings {
  @override
  void dependencies() {
    Get.put(AuthController()); // 改为立即初始化
    Get.put(LanguageController());
    Get.put(SettingController()); // 立即初始化以检查noticeType
    Get.lazyPut(() => NavigationController());
    Get.put(HomeController()); // 改为立即初始化，因为启动流程需要使用
    Get.lazyPut(() => ContractController());
    Get.lazyPut(()=> WalletController());
    Get.lazyPut(()=> InviteController());
  }
}
